<template>

    <!-- <div style="padding-top: 44px;"> -->
    <div class="goodsDetailContainer" style="padding-top: 0px;" ref="goodsDetailContainer">
        <!-- <i class="van-icon van-icon-arrow-left van-nav-bar__arrow" slot="nav-left" @click="$router.back()"></i>
        <van-tabs v-model="active" class="vanTabs" @click="changeTag">
            <van-tab title="商品详情"> </van-tab>
            <van-tab title="评价"></van-tab>
            <van-tab title="详情"></van-tab>
            <i class="van-icon van-icon-arrow-left van-nav-bar__arrow" slot="nav-left" @click="$router.back()"></i>
        </van-tabs> -->

        <!-- 滚动时出现回到顶部图标 -->
        <img src="../../static/img/backTop.png" class="backTop" @click="backTop" v-show="flag_scroll" />
        <div class="goodsBox" ref="goodsBox" :style="{height: bodyHeight + 'px'}">
            <div class="scrollGoodsBox" ref="scrollGoodsBox">
                <div id="goods" ref="goods">
                    <van-swipe :autoplay="3000" indicator-color="white">
                        <van-swipe-item v-for="item in shopGoodsImgList" :key="item.imgId">
                            <img :src="`/images${item.imagePath}`" alt="" srcset="" class="bannerImg">
                        </van-swipe-item>
                    </van-swipe>
                    <!-- 固定顶部返回按钮样式！！！！ -->
                    <div style="position: absolute; top: 0; left: 0; color: #ff6700; z-index: 998; padding: 15px; width: 100%;">
                        <img src="../../static/img/iconBack.png" style="width:25px;" @click="$router.back()"/>
                        <img src="../../static/img/sharebtn.png" style="width:25px; float:right;" @click="fetchData()"/>
                    </div>
                    <div class="goodsInfo">
                        <div id='favWrap'>
                            <div class="goodsName">{{shopGoods.simpleTitle}}</div>
                            <div class="goodsNameSub">{{shopGoods.title}}</div>
                            <!-- <div class="favour" @click="start">
                                <van-icon name="star-o" size="20px" :color="collectStatus == 1 ? '#f44' : ''"></van-icon>
                                <p v-if="collectStatus == 0">收藏</p>
                                <p v-else>已收藏</p>
                            </div> -->
                        </div>


                        <div class="goodsOther">
                            <div class="goodsPrice" v-if="stageNum!=1"><!--此处修改产品价格为分期展示-->
                                ¥
                                <em v-if="specInfo.id">{{(specInfo.price/stageNum) | money}}*{{stageNum}}期</em><!-- |money保留两位小数 -->
                                <!-- <em v-else>{{(specInfo.minMoney)/stageNum | money}}*{{stageNum}}期 - {{(specInfo.maxMoney)/stageNum | money}}*{{stageNum}}期</em> -->
                                <em v-else>{{(specInfo.minMoney)/stageNum | money}}*{{stageNum}}期</em>
                                <!-- <span v-if="specInfo.oldPrice">¥{{specInfo.oldPrice | money}}</span> --><!--去掉划线价-->
                            </div>
                            <div class="goodsPrice" v-else>
                                ¥
                                <em v-if="specInfo.id">{{(specInfo.price) | money}}</em><!-- |money保留两位小数 -->
                                <!-- <em v-else>{{(specInfo.minMoney) | money}} - {{(specInfo.maxMoney) | money}}</em> -->
                                <em v-else>{{(specInfo.minMoney) | money}}</em>
                            </div>
                            <!-- <span class="count">销量 {{shopGoods.showSoldNum || 0}} 件</span> -->
                        </div>
                    </div>

                    <div class="panelListContent">
                        <div class="panelList">
                            <van-cell v-if="shopGoods.noSku == 1" title="已选" style="background: #fafafa; margin: 0; border-radius: 8px;" :value="specInfo.id ? specInfo.name + '*' +goodsNum : '请选择产品规格'"></van-cell>
                            <van-cell v-else title="已选" is-link style="background: #fafafa; margin: 0; border-radius: 8px;" :value="specInfo.id ? specInfo.name + '*' +goodsNum : '请选择产品规格'" @click.native="showSku = true"></van-cell>

                            <van-cell title="评价" is-link :value="commentList.length == 0 ? '暂无评价' : '共'+commentTotal+'条评价'" style="background: #fafafa; margin: 0; border-radius: 8px;" @click="$router.push('/goods/comment/' + goodsId)"></van-cell>
                            <van-cell style="background: #fafafa; margin: 0; border-radius: 8px;">
                                <template slot="title">
                                    <span class="custom-text" style="font-size:12px; color:#9b9b9b;"><!--自定义图标gou-->
                                        <van-icon class-prefix="my-icon" name="gou" />小米自营
                                        <van-icon class-prefix="my-icon" name="gou" />小米发货
                                        <van-icon class-prefix="my-icon" name="gou" />1年保修
                                    </span>
                                </template>
                            </van-cell>
                        </div>
                    </div>
                </div>

                <div class="evaluate" ref="evaluate"> 
                    <van-cell title="商品评价"  :value="commentList.length == 0 ? '暂无评价' : '共有'+commentTotal+'条评价'" style="margin-top: 10px;"></van-cell>
                    <div v-if="commentList.length > 0">
                        <van-tag plain  size="large" @click="commentType = '';getGoodsCommentList()">全部</van-tag>
                        <van-tag plain size="large" @click="commentType = 'good';getGoodsCommentList()">好评</van-tag>
                        <van-tag plain size="large" @click="commentType = 'common';getGoodsCommentList()">中评</van-tag>
                        <van-tag plain size="large" @click="commentType = 'bad';getGoodsCommentList()">差评</van-tag>
                    </div>

                    <ul>
                        <li v-for="(item, index) in commentList" v-bind:key="index">
                            <div class="header">
                                <div class="name">
                                    {{item.userNickName}} <van-rate disabled disabled-color="#ffd21e" v-model="item.starNum" :size="12"></van-rate>
                                </div>

                                <div class="time">{{item.commentTime.split ? item.commentTime.split(' ')[0] : item.commentTime}}</div>
                            </div>

                            <div class="content">
                                {{item.commentContent}}
                            </div>
                        </li>
                        <div class="more" v-if="commentTotal > 0" @click="$router.push('/goods/comment/' + goodsId)">查看更多<van-icon name="arrow" /></div>
                    </ul>
                </div>
                <van-cell-group style="margin-top: 10px; display:none;">
                    <van-cell :title="shopName" icon="shop-o" value="进入店铺" is-link @click="$router.push('/goods/list?shopid=' + shopGoods.shopId)"></van-cell>
                </van-cell-group>

                <div class="goodsDetail" ref="goodsDetail">
                    <div class="tabs">
                        <div class="tab_item" :class="{active: activeTab === 'img'}" @click="activeTab = 'img'">
                            图文详情
                        </div>
                        <div class="tab_item" :class="{active: activeTab === 'table'}" @click="activeTab = 'table'">
                            规格参数
                        </div>
                    </div>
                    <div class="imgList" v-show="activeTab === 'img'" v-html="shopGoods.description">
                    </div>

                    <div class="tableDetail"  v-show="activeTab === 'table'">
                        <van-cell title="基本信息"></van-cell>
                        <div class="table">
                            <p>
                                <span class="key">名称</span>
                                <span class="value">{{shopGoods.simpleTitle}}</span>
                            </p>
                            <p>
                                <span class="key">类型</span>
                                <span class="value">{{shopGoods.categoryName}}</span>
                            </p>
                            <p v-for="(kValue,index) in sku.tree" v-bind:key="index">
                                <span class="key">{{kValue.k}}</span>
                                <span class="value" v-for="(kValueItem,indexElse) in kValue.v" v-bind:key="indexElse">
                                    {{kValueItem.name}}<span v-if="indexElse!=(kValue.v.length-1)">、</span>
                                </span>
                            </p>
                            <!-- <p v-if="specInfo.id">
                                <span class="key">{{sku.tree[0].k}}</span>
                                <span class="value">{{specInfo.name}}</span>
                            </p>
                            <p v-if="specInfo.id"> 
                                <span class="key">{{sku.tree[1].k}}</span>
                                <span class="value">{{specInfo.netWeight + '' + specInfo.netWeightUnit}}</span>
                            </p> -->
                            <div style="height: 30px;"> </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        

        <div class="selfFixDivMask" style="width: 100%; height: 50px; position: fixed; bottom: 0;">
            <div class="selfFixDiv">
                <div style="flex: 1; text-align: center; display: flex; justify-content: space-around; align-items: center; flex-direction: row; align-content: center; font-size: 12px; height: 50px;">
                    <div style="flex: 1; text-align: center;" @click="$router.push('/index')"><img src="../../static/img/shouye.png" style="width: 20px;"/><span style="display: block;">首页</span></div>
                    <div style="flex: 1; text-align: center;" @click="start">
                        <img src="../../static/img/xihuan.png" style="width: 20px;" v-if="collectStatus == 0"/>
                        <img src="../../static/img/xihuan1.png" style="width: 20px;" v-else/>
                        <span style="display: block;">喜欢</span>
                    </div>
                </div>
                <div v-if="shopGoods.status == 1 && shopGoods.noSku != 1" style="flex: 1; text-align: center; background: #ff7600; color: #fff; font-size: 16px; height: 50px; line-height: 50px;" @click="buyIt">立即购买</div>
                <!-- 库存不足 -->
                <div v-if="shopGoods.status == -1 || shopGoods.status == 0" style="flex: 1; text-align: center; background: #979797; color: #fff; font-size: 16px; height: 50px; line-height: 50px;" disabled="disabled">已下架</div>
                <!-- 未添加规格信息的做暂时缺货处理 添加noSku属性=1 -->
                <div v-if="shopGoods.status == 1 && shopGoods.noSku == 1" style="flex: 1; text-align: center; background: #979797; color: #fff; font-size: 16px; height: 50px; line-height: 50px;" disabled="disabled">暂时缺货</div>
            </div>
        </div>

        <!-- <van-goods-action>
            <van-goods-action-mini-btn
                icon="wap-home"
                text="首页"
                @click="$router.push('/shopCar')"
            />
            <van-goods-action-mini-btn
                icon="like-o"
                text="喜欢"
                @click="$router.push('/shopCar')"
            />
            <van-goods-action-mini-btn
                v-if="cartCount > 0"
                :info="cartCount"
                icon="cart-o"
                text="购物车"
                @click="$router.push('/shopCar')"
            />
            <van-goods-action-mini-btn
                v-else
                icon="cart-o"
                text="购物车"
                @click="$router.push('/shopCar')"
            />
            <van-goods-action-mini-btn
                icon="shop-o"
                text="店铺"
                @click="$router.push('/goods/list?shopid=' + shopGoods.shopId)"
            />
            <van-goods-action-big-btn text="加入购物车" :disabled="true" @click="joinCar"/>
            <van-goods-action-big-btn
                primary
                text="立即购买"
                @click="buyIt"
            />
        </van-goods-action> -->


        <van-sku 
            @sku-selected="skuSelect"
            v-model="showSku" 
            :goods-id="goodsId" 
            :sku="sku"
            :initial-sku="initialSku"
            :hide-stock="true"
            close-on-click-overlay	
            @add-cart="joinCar"
            @buy-clicked="buyIt"
            @stepper-change="numberChange"
            :show-add-cart-btn="false"
            :goods="goodsInfoforSKU"></van-sku>

        <!--分享遮罩-->
        <div v-if="showShareMask" @click="fetchData()" style="width:100%; height:100%; background: rgba(0,0,0,0.5); position:fixed; top:0; left:0; z-index:999;">
            <img src="../../static/img/share.png" style="width:100%; margin-top:15px;"/>
        </div>
    </div>
</template>

<script>
import BScroll from 'better-scroll';
import { ImagePreview } from 'vant';
import wx from 'weixin-js-sdk';
export default {
    name: 'goodsDetail',
    data() {
        return {
            // bodyHeight: Number(localStorage.getItem('bodyHeight')) - 44 - 50,
            bodyHeight: Number(localStorage.getItem('bodyHeight')) - 50,
            goodsDetailRoot: null,
            shopName: '', //店铺名称
            active: 0, //头部选中的
            activeTab: 'img',//图文详情还是商品详情
            goodsId: '',//商品ID
            spceId: '',//规格ID

            collectStatus: 0, //是否收藏 1是 0否
            cartCount: 0,  //购物车竖来
            rank: 4, //

            commentType: '', //'' 全部 bad：差评 common:中评 good：好评
            commentList: [],
            commentTotal: 0,

            _stack: {}, //初始规格信息 xx - xx
            specInfo: {}, //当前规格信息
            shopGoods: {}, //商品信息
            shopGoodsImgList: {}, //商品轮播图
            stageNum: 0, // 分期期数
            goodsNum: 1,

            isNodata: false, // 商品是否存在
            flag_scroll: false, //默认不展示回到顶部滚动图标

            showSku: false,
            goodsInfoforSKU: {
                title: '',
                picture: ''
            },

            sku: {
                // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
                // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
                tree: [
                    
                ],
                // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
                list: [''
                ],
            },

            initialSku: {
                selectedNum: 1
            },

            recommandMarketCode: '', //推荐人营销代码
            showShareMask: false, //是否显示分享遮罩层

        }
    },


    methods: {
        // shopImagePreview() {
        //     ImagePreview({ images: this.shopGoodsImgList.map(e => `/images${e.imagePath}`), startPosition:0,    //图片预览起始位置索引 默认 0
        //             showIndex: true,    //是否显示页码         默认 true
        //             showIndicators: true, //是否显示轮播指示器 默认 false
        //             loop:false,            //是否开启循环播放  貌似循环播放是不起作用的。。。
        //             onClose:function (url) {  //回调参数,官方文档解释的不是很清楚。。。
        //                 //回调参数类型 url:{ index:Number(当前图片的索引值), url:当前图片的URL }
        //                 var num = url.index, url_link = url.url;
        //                 console.log(url);
        //             }})
        // },
        changeTag(index) {
            let div = ['goods', 'evaluate', 'goodsDetail'];
            this.goodsDetailRoot.scrollToElement(this.$refs[div[index]], 300);
        },
        getShopDetail() {
            this.$http.get('/shop/goods/front/getGoodsDetail?goodsId=' + this.goodsId + '&token=' + localStorage.getItem('token')).then(res => {
                console.log('获取产品详情成功')
                console.log(res.data)
                if (res.status === 0) {
                    this.collectStatus = res.data.collectStatus; // 是否收藏
                    this.cartCount = res.data.cartCount;
                    this.shopName = res.data.shopName;
                    this.shopGoods = res.data.shopGoods; // 产品信息
                    this.stageNum = res.data.stageNum; // 分期期数
                    this.shopGoodsImgList = res.data.shopGoodsImgList || [`/images/${this.shopGoods.titleImage}`];
                    
                    this.goodsInfoforSKU = {
                        title: this.shopGoods.name,
                        picture: `/images/${this.shopGoods.titleImage}`
                    }
                    
                    let shopGoodsSpecList = res.data.shopGoodsAttrList || []; // 产品规格信息
                    let rule = [];
                    let maxMoney = 0;
                    let minMoney = 0;
                    let stock_num = 0;
                    let _stack = shopGoodsSpecList.map(e => {
                        rule.push({
                            id: e.spceId, // skuId，下单时后端需要
                            name: e.name,
                            price: e.memberPrice, // 价格（单位分）
                            oldPrice: e.price,
                            // s1: e.spceId, // 规格类目 k_s 为 s1 的对应规格值 id
                            rule: e.spceId, // 规格类目 k_s 为 s1 的对应规格值 id
                            stock_num: e.stockQuantity, // 当前 sku 组合对应的库存
                            netWeight: e.netWeight, //重量
                            netWeightUnit: e.netWeightUnit, //重量单位
                        });
                        stock_num += e.stockQuantity;
                        if (maxMoney === 0) {
                            maxMoney = e.memberPrice;
                        } else if (e.memberPrice > maxMoney) {
                            maxMoney = e.memberPrice;
                        }
                        if (minMoney === 0) {
                            minMoney = e.memberPrice;
                        } else if (e.memberPrice < minMoney) {
                            minMoney = e.memberPrice;
                        }
                        return {
                            id: e.spceId,
                            name: e.name,
                            imgUrl: `/images/${this.shopGoods.titleImage}`
                        }
                    })
                    console.log('_stack')
                    console.log(_stack)

                    // 理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值（k_s）[对应list规格值]

                    this.sku.tree.push(
                        {
                            k: '版本', // skuKeyName：规格类目名称
                            v: _stack,
                            // k_s: 's1'
                            k_s: 'rule' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                        },{
                            k: '版本1', // skuKeyName：规格类目名称
                            v: _stack,
                            // k_s: 's1'
                            k_s: 'rule1' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                        }
                    );
                    // this.sku.tree.push({
                    //     k: '颜色', // skuKeyName：规格类目名称
                    //     v: _stack,
                    //     // k_s: 's1'
                    //     k_s: 'rule' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                    // });

                    console.log('sku_list')
                    console.log(rule)

                    this.sku.list = rule;
                    
                    this._stack = {
                        // maxMoney, minMoney
                        minMoney
                    };

                    if (shopGoodsSpecList.length === 1) {
                        this.spceId = rule[0].id;
                        // this.initialSku.s1 = this.spceId;
                        this.initialSku.rule = this.spceId;
                        this.specInfo = rule[0];
                    } else {
                        this.specInfo = {
                            // maxMoney, minMoney
                            minMoney
                        };
                        // this.sku.price = (minMoney / 100).toFixed(2) + '-' + (maxMoney / 100).toFixed(2);
                        this.sku.price = (minMoney / 100).toFixed(2)
                    }

                    this.sku.stock_num = stock_num;

                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.goodsDetailRoot.refresh();
                        }, 500)
                    })

                    // 如果商品不存在跳转回首页继续购物
                    if (this.isNodata) {
                         this.$router.push({path: '/goods/noGoodsdata'});
                    }
                }
            })
        },

        getShopDetailNew() {
            this.$http.get('/shop/goods/front/getGoodsDetail?goodsId=' + this.goodsId + '&token=' + localStorage.getItem('token')+'&recommandMarketCode=' + this.recommandMarketCode).then(res => {
                console.log('获取产品详情成功')
                console.log(res.data)
                if (res.status === 0) {
                    this.collectStatus = res.data.collectStatus;
                    this.cartCount = res.data.cartCount;
                    this.shopName = res.data.shopName;
                    this.shopGoods = res.data.shopGoods; // 产品信息
                    this.stageNum = res.data.stageNum; // 分期期数
                    this.shopGoodsImgList = res.data.shopGoodsImgList || [`/images/${this.shopGoods.titleImage}`];
                    console.log('默认规格图片：'+`/images/${this.shopGoods.titleImage}`)
                    this.goodsInfoforSKU = {
                        title: this.shopGoods.name,
                        picture: `/images/${this.shopGoods.titleImage}`
                    }
                    
                    console.log('shopGoodsSpecList')
                    console.log(res.data.shopGoodsSpecList)

                    let shopGoodsGroupList = res.data.shopGoodsAttrList || []; // 产品规格信息组合
                    
                    // 未添加规格参数的做暂时缺货处理
                    if (res.data.shopGoodsAttrList.length == 0) {
                        this.shopGoods.noSku = 1
                    }
                    
                    let _stack1 = []
                    let _stack2 = []
                    let _stack3 = []
                    let _stackStr1,_stackStr2,_stackStr3
                    for (var i = 0; i < shopGoodsGroupList.length; i++) {
                        console.log(shopGoodsGroupList[i].modelAttrName)
                        console.log(shopGoodsGroupList[i].shopGoodsAttrValueList)

                        // var x = '_stackStr'+i+1
                        // console.log('123_'+x)
                        // x = shopGoodsGroupList[i].modelAttrName

                        if (i == 0) {
                            _stackStr1 = shopGoodsGroupList[i].modelAttrName
                            _stack1 = shopGoodsGroupList[i].shopGoodsAttrValueList.map(e => {
                                return {
                                    id: e.goodsAttrValueId,
                                    name: e.modelAttrValueName,
                                    imgUrl: `/images/` + e.imageUrl
                                }
                            })
                        } else if (i == 1) {
                            _stackStr2 = shopGoodsGroupList[i].modelAttrName
                            _stack2 = shopGoodsGroupList[i].shopGoodsAttrValueList.map(e => {
                                return {
                                    id: e.goodsAttrValueId,
                                    name: e.modelAttrValueName,
                                    imgUrl: `/images/` + e.imageUrl
                                }
                            })
                        } else if (i == 2) {
                            _stackStr3 = shopGoodsGroupList[i].modelAttrName
                            _stack3 = shopGoodsGroupList[i].shopGoodsAttrValueList.map(e => {
                                return {
                                    id: e.goodsAttrValueId,
                                    name: e.modelAttrValueName,
                                    imgUrl: `/images/` + e.imageUrl
                                }
                            })
                        }
                    }
                    // console.log("_stack1")
                    // console.log(_stack1)
                    // console.log("_stack2")
                    // console.log(_stack2)

                    let shopGoodsSpecList = res.data.shopGoodsSpecList || []; // 产品规格信息全部情况组合
                    let rule = [];
                    let maxMoney = 0;
                    let minMoney = 0;
                    let stock_num = 0;
                    let _stack = shopGoodsSpecList.map(e => {
                        rule.push({
                            id: e.spceId, // skuId，下单时后端需要
                            name: e.name,
                            price: e.memberPrice, // 价格（单位分）
                            oldPrice: e.price,
                            // s1: e.spceId, // 规格类目 k_s 为 s1 的对应规格值 id
                            s1: e.s1, // 规格类目 k_s 为 s1 的对应规格值 id
                            s2: e.s2, // 规格类目 k_s 为 s1 的对应规格值 id
                            s3: e.s3, // 规格类目 k_s 为 s1 的对应规格值 id
                            stock_num: e.stockQuantity, // 当前 sku 组合对应的库存
                            netWeight: e.netWeight, //重量
                            netWeightUnit: e.netWeightUnit, //重量单位
                        });
                        stock_num += e.stockQuantity;
                        if (maxMoney === 0) {
                            maxMoney = e.memberPrice;
                        } else if (e.memberPrice > maxMoney) {
                            maxMoney = e.memberPrice;
                        }
                        if (minMoney === 0) {
                            minMoney = e.memberPrice;
                        } else if (e.memberPrice < minMoney) {
                            minMoney = e.memberPrice;
                        }
                        // return {
                        //     id: e.spceId,
                        //     name: e.name,
                        //     imgUrl: `/images/${this.shopGoods.titleImage}`
                        // }
                    })
                    // console.log('_stack')
                    // console.log(_stack)

                    // 理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值（k_s）[对应list规格值]
                    if (_stack1.length!=0) {
                        this.sku.tree.push(
                        {
                            k: _stackStr1, // skuKeyName：规格类目名称
                            v: _stack1,
                            k_s: 's1' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                        })
                    } else {
                        console.log('_stack1==0')
                    }
                    if (_stack2.length!=0) {
                        this.sku.tree.push(
                        {
                            k: _stackStr2, // skuKeyName：规格类目名称
                            v: _stack2,
                            k_s: 's2' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                        })
                    } else {
                        console.log('_stack2==0')
                    }
                    if (_stack3.length!=0) {
                        this.sku.tree.push(
                        {
                            k: _stackStr3, // skuKeyName：规格类目名称
                            v: _stack3,
                            k_s: 's3' // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
                        })
                    } else {
                        console.log('_stack3==0')
                    }

                    console.log('sku_list')
                    console.log(rule)
                    console.log('_sku_tree')
                    console.log(this.sku.tree)

                    this.sku.list = rule;
                    
                    this._stack = {
                        // maxMoney, minMoney
                        minMoney
                    };
                    console.log('this.initialSku')
                    console.log(this.initialSku)
                    // 问题出在这里！！！！好好看一下
                    if (shopGoodsSpecList.length === 1) {
                        // console.log(rule)
                        this.spceId = rule[0].id;
                        // this.initialSku.s1 = this.spceId;
                        this.initialSku.rule = rule;
                        console.log(this.initialSku)
                        this.specInfo = rule[0];
                    } else {
                        this.specInfo = {
                            // maxMoney, minMoney
                            minMoney
                        };
                        // this.sku.price = (minMoney / 100).toFixed(2) + '-' + (maxMoney / 100).toFixed(2);
                        this.sku.price = (minMoney / 100).toFixed(2)
                    }
                    console.log('this.specInfo')
                    console.log(this.specInfo)

                    this.sku.stock_num = stock_num;
                    
                    console.log('this.sku')
                    console.log(this.sku)

                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.goodsDetailRoot.refresh();
                        }, 500)
                    })

                    // 如果商品不存在跳转回首页继续购物
                    if (this.isNodata) {
                         this.$router.push({path: '/goods/noGoodsdata'});
                    }
                }
            })
        },

        joinCar() {
            if (!this.spceId) {
                this.showSku = true;
                return;
            }
            this.$http.post('/shop/shoppingCart/front/addShoppingCart', {
                goodsId: this.goodsId,
                specId: this.spceId,
                productNum: this.goodsNum,
            }).then(res => {
                if (res.status === 0) {
                    this.$toast.success('加入成功');
                    this.cartCount = Number(res.data) || 0;
                    this.showSku = false;
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        buyIt() {
            console.log(this.spceId)
            console.log('click 立即购买')
            if (!this.spceId) {
                this.showSku = true;
                return;
            }
            this.$http.post('/shop/order/front/immediatePurchase', {
                goodsId: this.goodsId,
                specId: this.spceId,
                productNum: this.goodsNum,
            }).then(res => {
                if (res.status === 0) {
                    this.$router.push({path: '/order/payOrder', query: {order: res.data}});
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        numberChange(value) {
            this.goodsNum = value;
        },

        skuSelect({skuValue, selectedSku, selectedSkuComb}) {
            console.log('当前规格信息')
            console.log(this.specInfo)
            console.log('选中一级规格')
            console.log(skuValue)
            console.log('选中二级规格')
            console.log(selectedSku)
            
            if (skuValue.skuKeyStr == 's1'){
                this.goodsInfoforSKU.picture = skuValue.imgUrl
                // this.goodsInfoforSKU.picture = `/images/` + skuValue.imgUrl
            }

            if (!selectedSkuComb) {
                this.specInfo = Object.assign({}, this._stack);
                this.spceId = '';
                return;
            }
            console.log('--产品规格选择--')
            console.log(selectedSkuComb)
            this.specInfo = Object.assign({}, selectedSkuComb);
            this.spceId = selectedSkuComb.id;
            console.log('this.specInfo')
            console.log(this.specInfo)
        },


        start() {
            let collectStatus = this.collectStatus, url;
            if (collectStatus) {
                url = '/shop/goods/front/cancelCollection';
            } else {
                url = '/shop/goods/front/addCollection'
            }

            this.$http.post(url, {goodsId: this.goodsId}).then(res => {
                if (res.status === 0) {
                    if (collectStatus == 1) {
                        // this.$toast.success('取消成功');
                        this.collectStatus = 0;
                    } else {
                        // this.$toast.success('收藏成功');
                        this.collectStatus = 1;
                    }
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        //获取评价
        getGoodsCommentList() {
            this.$http.post('/shop/goods/front/getGoodsCommentList', {
                goodsId: this.goodsId,
                pageSize: 5,
                pageNum: 1,
                commentType: this.commentType, 
            }).then(res => {
                if (res.status === 0) {
                    this.commentList = res.data.rows || [];
                    this.commentTotal = res.data.total;
                }
            })
        },

        backTop(){
            this.goodsDetailRoot.scrollToElement(this.$refs.scrollGoodsBox, 300);
        },

        // 分享
        wxShare () {
            let _this = this
            this.$http.post('/weixin/wx/front/getWxShareInfo', {
                url: window.location.href,
                wxAppId: 1
            }).then(res => {
                if (res.status === 0) {
                    console.log(res.data)
                    var Data = res.data
                    wx.config({
                        debug: false, // 开启调试模式,开发时可以开启
                        appId: Data.appid,  // 必填，公众号的唯一标识  由接口返回
                        timestamp: Data.timestamp, // 必填，生成签名的时间戳 由接口返回
                        nonceStr: Data.noncestr,    // 必填，生成签名的随机串 由接口返回
                        signature: Data.signature,  // 必填，签名 由接口返回
                        //jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'] // 此处填你所用到的方法
                        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 此处填你所用到的方法

                    })
                    
                    wx.ready(()=>{
                        //分享给朋友
                        wx.updateAppMessageShareData({
                            title: '分享title', // 分享标题
                            desc: '分享描述', // 分享描述
                            link: window.location.href+'?marketCode='+localStorage.getItem('userMarketCode'), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: '', // 分享图标
                            type: '', // 分享类型,music、video或link，不填默认为link
                            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                            success: function () {
                                // 用户确认分享后执行的回调函数
                                this.$router.go(0);
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                                // alert('cancel')
                                _this.fetchData()
                            }
                        })

                        //分享到朋友圈
                        wx.updateTimelineShareData({
                            title: '分享title', // 分享标题
                            link: window.location.href+'?marketCode='+localStorage.getItem('userMarketCode'), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: '',
                            success: function () {
                                // 用户确认分享后执行的回调函数
                                this.$router.go(0);
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                                _this.fetchData()
                            }
                        })
                    })
                }
            })
        },

        fetchData() {
            // 判断用户是否登录（未登录获取不到用户营销代码不能进行分享操作）
            if (localStorage.getItem('userMarketCode')) {
                this.showShareMask=!this.showShareMask
            } else {
                this.$toast.fail('请先登录后分享')
                setTimeout(() => {
                    this.$router.push({path: '/mine'});
                }, 1500)
            }
        }
    },

    destroyed() {
        if (this.goodsDetailRoot && this.goodsDetailRoot.destroy) {
            this.goodsDetailRoot.destroy();
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.goodsDetailRoot = new BScroll(this.$refs.goodsBox, {tap: true, click: true});
            this.goodsDetailRoot.on('scrollEnd', (({x, y}) => {
                console.log('mounted!!!')
                y = Math.abs(y);
                console.log(y)
                let div = ['goods', 'evaluate', 'goodsDetail'], index = 0;
                let offset = div.map(e => {
                    return this.$refs[e].offsetTop;
                });
                console.log(offset)
                offset.forEach((e, i) => {
                    if (y >= e) {
                        index = i;   
                    }
                });
                if (y>=200) {
                    this.flag_scroll = true
                } else {
                    this.flag_scroll = false
                }
                this.active = index;
            }));
        })
    },

    created() {
        this.goodsId = this.$route.params.id;
        // this.getShopDetail();
        this.getShopDetailNew();
        this.getGoodsCommentList()

        this.wxShare(); // 右上角分享
    }
}
</script>

<style scoped lang="scss">
@import './../../assets/default.scss';
@font-face {
    font-family: 'iconfont';  /* project id 1531852 */
    src: url('//at.alicdn.com/t/font_1531852_joyr07mqzm.eot');
    src: url('//at.alicdn.com/t/font_1531852_joyr07mqzm.eot?#iefix') format('embedded-opentype'),
    url('//at.alicdn.com/t/font_1531852_joyr07mqzm.woff2') format('woff2'),
    url('//at.alicdn.com/t/font_1531852_joyr07mqzm.woff') format('woff'),
    url('//at.alicdn.com/t/font_1531852_joyr07mqzm.ttf') format('truetype'),
    url('//at.alicdn.com/t/font_1531852_joyr07mqzm.svg#iconfont') format('svg');
}
.my-icon {
    font-family:"iconfont" !important;
    font-size:20px;font-style:normal;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;
    vertical-align: middle;
    padding: 0 2px 0 6px;
}

.my-icon-heart::before {
  content: '\e641';
  color: #ff6700;
}
.my-icon-gou::before {
  content: '\e604';
  color: #ff6700;
}

.backTop{
    position: absolute;
    right: 15px;
    bottom: 80px;
    z-index: 2000;
    width: 50px;
}

.goodsBox {
    overflow: hidden;
    position: relative;
}
.vanTabs {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 12;
}
.van-icon-arrow-left {
    position: relative;
    top: 15px;
    left: 14px;
    color: $defaultColor;
    width: 30px;
    height: 40px;
}
.bannerImg {
    // height: 375px;
    width: 100%;
    touch-action: none;
}
#goods {
    /deep/ .van-cell__title { flex: none;}
}
.panelListContent{
    padding:0 15px 15px 15px;
    background: #fff;
}
.panelList{
    background: #fafafa;
    border: 1px solid #dddddd;
    border-radius: 8px;
    .van-cell__value{
        overflow : hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        padding-left: 5px;
    }
}
.goodsInfo {
    background-color: #fff;
    padding: 10px;
    padding-top: 12px;
    position: relative;
    #favWrap {
        min-height: 36px;
        // padding-right: 52px;
        // display: -webkit-box;
        // display: -webkit-flex;
        // display: flex;
        // -webkit-box-align: center;
        // -webkit-align-items: center;
        // align-items: center;
        .favour {
            position: absolute;
            right: 0;
            top: 14px;
            display: inline-block;
            /* padding-top: 12px; */
            height: 36px;
            width: 50px;
            font-size: 10px;
            color: #333;
            text-align: center;
            &::after {
                content: "";
                width: 0;
                display: block;
                border-left: 1px solid #ddd;
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
            }
        }
    }
    .goodsName {
        position: relative;
        color: #3c3c3c;
        overflow: hidden;
        font-size: 16px;
        font-weight: 400;
        line-height: 20px;
        padding-bottom: 10px;
        font-weight: bold;
    }
    .goodsNameSub{
        position: relative;
        color: #3c3c3c;
        overflow: hidden;
        font-size: 14px;
        line-height: 20px;
    }

    .goodsOther {
        display: flex;
        justify-content: space-between;
        align-items:flex-end;
        padding: 10px 0;
        .goodsPrice {
            font-size: 12px;
            color: #ff6700;
            font-weight: 600;
            line-height: 1.3;
            em {
                font-size: 18px;

            }
            span {
                color: #666;
                text-decoration: line-through;
                margin-left: 5px;
                display: inline-block;
            }
        }

        .count {
            font-size: 12px;
            color: #666;
        }
    }
}


.evaluate {
    background-color: #fff;
    /deep/ .van-tag {
        margin: 10px 5px 10px 10px;
    }
    display: none; // 隐藏商品评价模块

    ul {
        padding: 0 10px;
        li {
            padding: 10px 0;
            border-bottom: 1px solid #ebedf0;
            &:last-child {
                border: none;
            }
            .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                color: #999;
                font-size: 12px;
                /deep/ .van-rate {
                    display: inline-block;
                    vertical-align: middle;
                }
            }


            .content {
                position: relative;
                line-height: 1.3;
                margin: 5px 0;
                word-break: break-all;
                overflow: hidden;
            }
        }
    }

    .more { height: 45px; display: flex; align-items: center; justify-content: center; }
}

.goodsDetail {
    background-color: #fff;
    // margin-top: 10px;
    .tabs {
        height: 50px;
        width: 100%;
        overflow: hidden;
        // border-bottom: 1px solid #ddd;
        display: flex;
        .tab_item {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            height: 50px;
            line-height: 50px;
            // border-left: 1px solid #ddd;
            text-decoration: none;
            text-align: center;
            font-size: 14px;
            color: #333;
            background: #f3f3f3;
            &.active {
                color: #ff6700;
            }
        }
    }
    /deep/ .imgList > p {
        margin-top: -3px;
    }
    /deep/ .imgList > img {
        margin-top: -3px;
        width: 100% !important;
    }
    /deep/ .imgList img {
        width: 100% !important;
    }

    .tableDetail {
        .table {
            padding-left: 15px;
        }
        p {
            padding: 10px 15px 10px 0;
            display: flex;
            border-bottom: 1px solid #ebedf0;
            span {
                display: inline-block;
                &.key {
                    min-width: 100px;
                    max-width: 100px;
                    color: #666;
                }
            }
        }
    }
}

/deep/ .van-sku__goods-price{
    color: #ff6700;
    font-size: 16px;
}
/deep/ .van-sku-row__item{
    color: #434343;
    border-color: #dddddd;
}
/deep/ .van-sku-row__item--active{
    color: #ff6700;
    border-color: #ff6700;
    background: #ffffff;
}
/deep/ .van-button--bottom-action{
    background: #ff6700;
    border-radius: 50px;
    width: 90%;
    margin: 20px auto;
    height: 44px;
    line-height: 1;
}
/deep/ .van-ellipsis{
    white-space: pre-wrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: box;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-box;
    display: -o-box;
    line-clamp: 2;
    -webkit-line-clamp: 2;
    -moz-line-clamp: 2;
    -ms-line-clamp: 2;
    -o-line-clamp: 2;
    box-orient: vertical;
    -webkit-box-orient: vertical;
    -ms-box-orient: vertical;
    -o-box-orient: vertical;
    word-break: break-all;
    box-align: center;
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-box-align: center;
    -o-box-align: center;
    box-pack: center;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-box-pack: center;
    -o-box-pack: center;
    position: relative;
}
/deep/ .van-sku-header__img-wrap{
    margin-top: 0;
    height: 100px;;
    background: #fff;
}
/deep/ .van-sku-header__goods-info{
    min-height: 100px;
}
.selfFixDiv{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: row;    
}
</style>
